package com.bq.gametrade.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.BankCardList;
import com.bq.gametrade.bean.BankCardListDetails;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.BankPromptDialog;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.view.PayPasswordValidationView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class BankCardListActivity extends BaseActivity implements View.OnClickListener, BankPromptDialog.OnClickPressListener {

    private ImageView back, addBankCard;
    private TextView tvTitle;

    private ListView listView;
    private LinearLayout layPrompt;
    private ArrayList<BankCardListDetails> bankCardLists = new ArrayList<>();
    private BlankCardAdapter adapter = new BlankCardAdapter();
    private LoadingProgressDialog progressDialog;
    private UserInfoDetails userInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bankcard_list);
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        progressDialog = new LoadingProgressDialog(this, "正在解除绑定···");

        initView();

    }


    @Override
    protected void onResume() {
        super.onResume();
        getBankCardList();
    }


    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("银行卡管理");
        addBankCard = serchViewById(R.id.iv_userService);
        addBankCard.setOnClickListener(this);
        layPrompt = serchViewById(R.id.lay_prompt);
        listView = serchViewById(R.id.bank_card_list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BankPromptDialog dialog = new BankPromptDialog();
                Bundle bundle = new Bundle();
                bundle.putString("bankCardId", bankCardLists.get(position).id);
                dialog.setArguments(bundle);
                dialog.show(getSupportFragmentManager(), "");


            }
        });

    }


    /***
     * 进行解绑操作
     *
     * @param id
     */
    @Override
    public void OnListener(String id) {
        toPay(id);
    }

    /**
     * 验证支付密码-----start
     */

    private void toPay(final String bankId) {
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(BankCardListActivity.this, userInfo, progressDialog);
        payPasswordValidationView.showAtLocation(BankCardListActivity.this.findViewById(R.id.activity_bankcardList),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    removeBankCard(bankId);
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.iv_userService:
                startActivity(new Intent(BankCardListActivity.this, BankCardAddActivity.class));
                break;
        }
    }

    /**
     * 获取绑定银行卡列表
     */
    private void getBankCardList() {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        showSpotsDialog();
        VRHttp.geBindBankcardList(BankCardListActivity.this, HttpLink.GET_BANKCARD_LIST_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    layPrompt.setVisibility(View.GONE);
                    BankCardList bankCardList = (BankCardList) response;
                    if (bankCardList.status.equals("0")) {
                        bankCardLists = bankCardList.card_list;
                        if (bankCardLists.size() > 0) {
                            adapter.setData(bankCardLists);
                            adapter.notifyDataSetChanged();
                            layPrompt.setVisibility(View.GONE);
                        } else {
                            layPrompt.setVisibility(View.VISIBLE);
                        }

                    } else if (bankCardList.status.equals("99")) {
                        toastShow("登录超时，请重新登录");
                        application.setUserInfo(null);
                        startActivity(new Intent(BankCardListActivity.this, LoginActivity.class));
                        finish();
                    } else if (bankCardList.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(BankCardListActivity.this, LoginActivity.class));
                        finish();
                    } else {
                        toastShow("获取银行卡列表失败！请重试");
                    }
                } else {
                    layPrompt.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("获取银行卡列表失败！");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }

    /***
     *
     */
    private void removeBankCard(String bankCardId) {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("id", bankCardId);
        VRHttp.sendRequest(BankCardListActivity.this, HttpLink.BANKCARD_REMOVE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("解除银行卡成功");
                        getBankCardList();
                    } else if (bean.status.equals("99")) {
                        toastShow("登录超时，请重新登录");
                        application.setUserInfo(null);
                        startActivity(new Intent(BankCardListActivity.this, LoginActivity.class));
                        finish();
                    } else if (bean.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(BankCardListActivity.this, LoginActivity.class));
                        finish();
                    } else {
                        toastShow("解除银行卡失败！请重试");
                    }
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("解除失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });

    }


    class BlankCardAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return bankCardLists.size();
        }

        @Override
        public Object getItem(int position) {

            return bankCardLists.get(position);
        }

        public void setData(ArrayList<BankCardListDetails> list) {
            bankCardLists = list;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(BankCardListActivity.this).inflate(R.layout.listview_item_bankcard, null);
                viewHolder.bank_icon = (ImageView) convertView.findViewById(R.id.bank_icon);
                viewHolder.banCardName = (TextView) convertView.findViewById(R.id.ban_name);
                viewHolder.bankCardNumber = (TextView) convertView.findViewById(R.id.bank_number);
                viewHolder.bankCardBg = (RelativeLayout) convertView.findViewById(R.id.lay_bankCardBg);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            final BankCardListDetails card = bankCardLists.get(position);
//            int iconId = getBankIconId(card.bank_name);
//            if (iconId != -1) {
//                viewHolder.bank_icon.setImageResource(imgs[iconId]);
//                viewHolder.bank_icon.setVisibility(View.VISIBLE);
//            } else {
//                viewHolder.bankCardNumber.setText(card.card_num);
//                viewHolder.bankCardNumber.setVisibility(View.VISIBLE);
//                viewHolder.bank_icon.setVisibility(View.GONE);
//            }
            viewHolder.banCardName.setText(card.bank_name);
            StringBuilder msg = new StringBuilder().
                    append(card.card_num.substring(0, 0))
                    .append("**** **** **** ")
                    .append(card.card_num.substring(card.card_num.length() - 4, card.card_num.length()));

            viewHolder.bankCardNumber.setText(msg);
            if (card.bank_name.contains("商") || card.bank_name.contains("平安") || card.bank_name.contains("中信")) {
                viewHolder.bankCardBg.setBackgroundResource(R.drawable.bank_card_item_red);
            } else {
                viewHolder.bankCardBg.setBackgroundResource(R.drawable.bank_card_item_blue);
            }

            return convertView;
        }
    }

    static class ViewHolder {
        ImageView bank_icon;
        TextView banCardName;
        TextView bankCardNumber;
        RelativeLayout bankCardBg;

    }


    private int[] imgs = {
            R.mipmap.bank_china, R.mipmap.bank_guangda,
            R.mipmap.bank_gongshang, R.mipmap.bank_guangdong,
            R.mipmap.bank_huaxia, R.mipmap.bank_jianse,
            R.mipmap.bank_minsheng, R.mipmap.bank_nongye,
            R.mipmap.bank_pufa, R.mipmap.bank_xingye,
            R.mipmap.bank_youzheng, R.mipmap.bank_zhaoshang,
            R.mipmap.bank_pingan, R.mipmap.bank_zhongxin,
            R.mipmap.bank_jiaotong};

    private int getBankIconId(String bankName) {
        if (bankName.equals("中国银行"))
            return 0;
        if (bankName.equals("中国光大银行"))
            return 1;
        if (bankName.equals("中国工商银行"))
            return 2;
        if (bankName.equals("广东发展银行"))
            return 3;
        if (bankName.equals("华夏银行"))
            return 4;
        if (bankName.equals("中国建设银行"))
            return 5;
        if (bankName.equals("民生银行"))
            return 6;
        if (bankName.equals("中国农业银行"))
            return 7;
        if (bankName.equals("上海浦东发展银行"))
            return 8;
        if (bankName.equals("兴业银行"))
            return 9;
        if (bankName.equals("中国邮政储蓄银行"))
            return 10;
        if (bankName.equals("中国招商银行"))
            return 11;
        if (bankName.equals("平安银行"))
            return 12;
        if (bankName.equals("中信银行"))
            return 13;
        if (bankName.equals("中国交通银行"))
            return 14;
        return -1;
    }


}
